//
//  YMNetworkManager.swift
//  YDOAProduct
//
//  Created by YDWY on 2017/5/17.
//  Copyright © 2017年 Allen. All rights reserved.
//

import UIKit
import Alamofire


//打印
class YMLog : NSObject {
    
    /*
       自定义log
     */
    static func log(item:Any){
        #if DEBUG
            print(item)
        #else
        
        #endif
    }
}






class YMNetworkManager: NSObject {

    static let  shareInstance = YMNetworkManager.init()
    //私有化 init 方法
    public override init() {}

}



//封装网络请求类
extension YMNetworkManager {
    //MARK:- GET 请求
   public func getRequest(urlString : String,params : [String : Any]? , success :  @escaping(_ response : [String : AnyObject]) -> (), failture : @escaping (_ error : Error) -> () ){
        guard  let str = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
               let url = URL(string: str)
            else{return print("接口转码失败")}
        //使用Alamofire进行网络请求时，调用该方法的参数都是通过getRequest(urlString， params, success :, failture :）传入的，而success传入的其实是一个接受           [String : AnyObject]类型 返回void类型的函数

        Alamofire.request(url, method: .get, parameters: params).responseJSON { (response) in
            
            /*这里使用了闭包*/
            //当请求后response是我们自定义的，这个变量用于接受服务器响应的信息
            //使用switch判断请求是否成功，也就是response的result
            switch response.result {
              
            case .success( _):
                    //当响应成功是，使用临时变量value接受服务器返回的信息并判断是否为[String: AnyObject]类型 如果是那么将其传给其定义方法中的success
                if let value = response.result.value as? [String : AnyObject] {
                   success(value)
                }
                
            case .failure(let error):
                failture(error)
                YMLog.log(item:"请求失败\(error)")
            }
        }
        
    }
    
    
    //MARK: - POST 请求
   open func postRequset(urlString : String, params : [String :Any]?, success : @escaping  (_ response :[String : AnyObject]) ->(), failture : @escaping (_ error : Error) ->()){
        guard  let str = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
            let url = URL(string: str)
            else{return print("接口转码失败")}
        Alamofire.request(url, method: .post, parameters: params).responseJSON { (response) in
            
            switch response.result {
            case .success(_):
                if let value = response.result.value as? [String : AnyObject] {
                       success(value)
                }
                
            case .failure(let  error):
                failture(error)
                YMLog.log(item:"请求失败\(error)")
                
            }
            
        }
        
        
        
    }
    
    
    //MARK: - 上传图片
    /// - Parameters:
    ///   - urlString: 服务器地址
    ///   - params: ["flag":"","userId":""] - flag,userId 为必传参数
    ///        flag - 666 信息上传多张  －999 服务单上传  －000 头像上传
    ///   - data: image转换成Data
    ///   - name: fileName
    ///   - success:
    ///   - failture:
    func upLoadImageRequest(urlString : String, params:[String:String], data: [Data], name: [String],success : @escaping (_ response : [String : AnyObject])->(), failture : @escaping (_ error : Error)->()){
        
        let headers = ["content-type":"multipart/form-data"]
        guard  let str = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
            let url = URL(string: str)
            else{return print("接口转码失败")}

        Alamofire.upload(multipartFormData: { (multipartFormData) in
            
            //666 多张图片上传
            let  flag = params["flag"]
            let userId = params["userId"]
            
           multipartFormData.append((flag?.data(using: .utf8))!, withName: "flag")
            multipartFormData.append((userId?.data(using: .utf8))!, withName: "userId")
            for i in 0..<data.count {
                multipartFormData.append(data[i], withName: "appPhoto", fileName: name[i], mimeType: "image/png")
            }
            
        },  to: url, headers: headers) { (encodingResult) in
            switch encodingResult {
            case .success(request: let upload, streamingFromDisk: _, streamFileURL: _):
                upload.responseJSON(completionHandler: { (response) in
                    if let value = response.result.value as?[String : AnyObject]{
                         success(value)
                    }
                    
                })
            case .failure(let encodingError):
                failture(encodingError)
            }
            

            }
        }
        
    }
    


